package com.song.boot.springstudy.netty.idle;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

// 客户端往服务端发送心跳包
public class HeartbeatClient {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8080;

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 读空闲超时时间（秒）
                            // 写空闲超时时间（秒）
                            // 读写空闲超时时间（秒）

                            // 添加字符串编解码器
                            pipeline.addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
                            pipeline.addLast("encoder", new StringEncoder(StandardCharsets.UTF_8));
                            // 添加IdleStateHandler，3秒没有写事件触发WRITER_IDLE事件
                            pipeline.addLast(new IdleStateHandler(0, 3, 0, TimeUnit.SECONDS));

                            // 自定义心跳处理Handler
                            pipeline.addLast(new HeartbeatClientHandler());
                        }
                    });

            // 连接服务器
            ChannelFuture future = bootstrap.connect(HOST, PORT).sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}